import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _regeneratorRuntime from "@babel/runtime/helpers/esm/regeneratorRuntime";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { CloseOutlined, CopyOutlined, NotificationOutlined, SettingOutlined } from '@ant-design/icons';
import { isBrowser, merge } from '@ant-design/pro-utils';
import { disable as darkreaderDisable, enable as darkreaderEnable, setFetchMethod as setFetch } from '@umijs/ssr-darkreader';
import { useUrlSearchParams } from '@umijs/use-params';
import { Alert, Button, ConfigProvider, Divider, Drawer, List, message, Switch } from 'antd-v4';
import omit from 'omit.js';
import useMergedState from "rc-util/es/hooks/useMergedState";
import { useEffect, useRef, useState } from 'react';
import defaultSettings from '../../defaultSettings';
import { getLanguage, gLocaleObject } from '../../locales';
import { genStringToTheme } from '../../utils/utils';
import BlockCheckbox from './BlockCheckbox';
import './index.less';
import LayoutSetting, { renderLayoutSettingItem } from './LayoutChange';
import RegionalSetting from './RegionalChange';
import ThemeColor from './ThemeColor';

var Body = function Body(_ref) {
  var children = _ref.children,
      prefixCls = _ref.prefixCls,
      title = _ref.title;
  return _jsxs("div", {
    style: {
      marginBottom: 24
    },
    children: [_jsx("h3", {
      className: "".concat(prefixCls, "-drawer-title"),
      children: title
    }), children]
  });
};

var getDifferentSetting = function getDifferentSetting(state) {
  var stateObj = {};
  Object.keys(state).forEach(function (key) {
    if (state[key] !== defaultSettings[key] && key !== 'collapse') {
      stateObj[key] = state[key];
    } else {
      stateObj[key] = undefined;
    }

    if (key.includes('Render')) stateObj[key] = state[key] === false ? false : undefined;
  });
  stateObj.menu = undefined;
  return stateObj;
};

export var getFormatMessage = function getFormatMessage() {
  var formatMessage = function formatMessage(_ref2) {
    var id = _ref2.id;
    var locales = gLocaleObject();
    return locales[id];
  };

  return formatMessage;
};

var updateTheme = /*#__PURE__*/function () {
  var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(dark, color) {
    var defaultTheme, defaultFixes;
    return _regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            if (!(typeof window === 'undefined')) {
              _context.next = 2;
              break;
            }

            return _context.abrupt("return");

          case 2:
            if (!(typeof window.MutationObserver === 'undefined')) {
              _context.next = 4;
              break;
            }

            return _context.abrupt("return");

          case 4:
            if (ConfigProvider.config) {
              _context.next = 6;
              break;
            }

            return _context.abrupt("return");

          case 6:
            ConfigProvider.config({
              theme: {
                primaryColor: genStringToTheme(color) || '#1890ff'
              }
            });

            if (dark) {
              defaultTheme = {
                brightness: 100,
                contrast: 90,
                sepia: 10
              };
              defaultFixes = {
                invert: [],
                css: '',
                ignoreInlineStyle: ['.react-switch-handle'],
                ignoreImageAnalysis: [],
                disableStyleSheetsProxy: true
              };

              if (window.MutationObserver && window.fetch) {
                setFetch(window.fetch);
                darkreaderEnable(defaultTheme, defaultFixes);
              }
            } else {
              if (window.MutationObserver) darkreaderDisable();
            }

          case 8:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));

  return function updateTheme(_x, _x2) {
    return _ref3.apply(this, arguments);
  };
}();
/**
 * 初始化的时候需要做的工作
 *
 * @param param0
 */


var initState = function initState(urlParams, settings, onSettingChange) {
  if (!isBrowser()) return;
  var replaceSetting = {};
  Object.keys(urlParams).forEach(function (key) {
    if (defaultSettings[key] || defaultSettings[key] === undefined) {
      if (key === 'primaryColor') {
        replaceSetting[key] = genStringToTheme(urlParams[key]);
        return;
      }

      replaceSetting[key] = urlParams[key];
    }
  });
  var newSettings = merge({}, settings, replaceSetting);
  delete newSettings.menu;
  delete newSettings.title;
  delete newSettings.iconfontUrl; // 同步数据到外部

  onSettingChange === null || onSettingChange === void 0 ? void 0 : onSettingChange(newSettings); // 如果 url 中设置主题，进行一次加载。

  if (defaultSettings.navTheme !== urlParams.navTheme && urlParams.navTheme) {
    updateTheme(settings.navTheme === 'realDark', urlParams.primaryColor);
  }
};

var getParamsFromUrl = function getParamsFromUrl(urlParams, settings) {
  if (!isBrowser()) return defaultSettings;
  return _objectSpread(_objectSpread(_objectSpread({}, defaultSettings), settings || {}), urlParams);
};

var genCopySettingJson = function genCopySettingJson(settingState) {
  return JSON.stringify(omit(_objectSpread(_objectSpread({}, settingState), {}, {
    primaryColor: settingState.primaryColor
  }), ['colorWeak']), null, 2);
};
/**
 * 可视化配置组件
 *
 * @param props
 */


var SettingDrawer = function SettingDrawer(props) {
  var _props$defaultSetting = props.defaultSettings,
      propsDefaultSettings = _props$defaultSetting === void 0 ? undefined : _props$defaultSetting,
      _props$settings = props.settings,
      propsSettings = _props$settings === void 0 ? undefined : _props$settings,
      hideHintAlert = props.hideHintAlert,
      hideCopyButton = props.hideCopyButton,
      _props$colorList = props.colorList,
      colorList = _props$colorList === void 0 ? [{
    key: 'daybreak',
    color: '#1890ff'
  }, {
    key: 'dust',
    color: '#F5222D'
  }, {
    key: 'volcano',
    color: '#FA541C'
  }, {
    key: 'sunset',
    color: '#FAAD14'
  }, {
    key: 'cyan',
    color: '#13C2C2'
  }, {
    key: 'green',
    color: '#52C41A'
  }, {
    key: 'geekblue',
    color: '#2F54EB'
  }, {
    key: 'purple',
    color: '#722ED1'
  }] : _props$colorList,
      getContainer = props.getContainer,
      onSettingChange = props.onSettingChange,
      enableDarkTheme = props.enableDarkTheme,
      _props$prefixCls = props.prefixCls,
      prefixCls = _props$prefixCls === void 0 ? 'ant-pro' : _props$prefixCls,
      _props$pathname = props.pathname,
      pathname = _props$pathname === void 0 ? window.location.pathname : _props$pathname,
      _props$disableUrlPara = props.disableUrlParams,
      disableUrlParams = _props$disableUrlPara === void 0 ? true : _props$disableUrlPara,
      themeOnly = props.themeOnly;
  var firstRender = useRef(true);

  var _useMergedState = useMergedState(false, {
    value: props.collapse,
    onChange: props.onCollapseChange
  }),
      _useMergedState2 = _slicedToArray(_useMergedState, 2),
      show = _useMergedState2[0],
      setShow = _useMergedState2[1];

  var _useState = useState(getLanguage()),
      _useState2 = _slicedToArray(_useState, 2),
      language = _useState2[0],
      setLanguage = _useState2[1];

  var _useUrlSearchParams = useUrlSearchParams({}, {
    disabled: disableUrlParams
  }),
      _useUrlSearchParams2 = _slicedToArray(_useUrlSearchParams, 2),
      urlParams = _useUrlSearchParams2[0],
      setUrlParams = _useUrlSearchParams2[1];

  var _useMergedState3 = useMergedState(function () {
    return getParamsFromUrl(urlParams, propsSettings || propsDefaultSettings);
  }, {
    value: propsSettings,
    onChange: onSettingChange
  }),
      _useMergedState4 = _slicedToArray(_useMergedState3, 2),
      settingState = _useMergedState4[0],
      setSettingState = _useMergedState4[1];

  var _ref4 = settingState || {},
      navTheme = _ref4.navTheme,
      primaryColor = _ref4.primaryColor,
      layout = _ref4.layout,
      colorWeak = _ref4.colorWeak;

  useEffect(function () {
    // 语言修改，这个是和 locale 是配置起来的
    var onLanguageChange = function onLanguageChange() {
      if (language !== getLanguage()) {
        setLanguage(getLanguage());
      }
    };
    /** 如果不是浏览器 都没有必要做了 */


    if (!isBrowser()) return function () {
      return null;
    };
    initState(getParamsFromUrl(urlParams, propsSettings), settingState, setSettingState);
    window.document.addEventListener('languagechange', onLanguageChange, {
      passive: true
    });
    return function () {
      return window.document.removeEventListener('languagechange', onLanguageChange);
    }; // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  useEffect(function () {
    updateTheme(settingState.navTheme === 'realDark', settingState.primaryColor);
  }, [settingState.primaryColor, settingState.navTheme]);
  /**
   * 修改设置
   *
   * @param key
   * @param value
   */

  var changeSetting = function changeSetting(key, value) {
    var nextState = {};
    nextState[key] = value;

    if (key === 'layout') {
      nextState.contentWidth = value === 'top' ? 'Fixed' : 'Fluid';
    }

    if (key === 'layout' && value !== 'mix') {
      nextState.splitMenus = false;
    }

    if (key === 'layout' && value === 'mix') {
      nextState.navTheme = 'light';
    }

    if (key === 'colorWeak' && value === true) {
      var dom = document.querySelector('body');

      if (dom) {
        dom.dataset.prosettingdrawer = dom.style.filter;
        dom.style.filter = 'invert(80%)';
      }
    }

    if (key === 'colorWeak' && value === false) {
      var _dom = document.querySelector('body');

      if (_dom) {
        _dom.style.filter = _dom.dataset.prosettingdrawer || 'none';
        delete _dom.dataset.prosettingdrawer;
      }
    }

    delete nextState.menu;
    delete nextState.title;
    delete nextState.iconfontUrl;
    delete nextState.logo;
    delete nextState.pwa;
    setSettingState(_objectSpread(_objectSpread({}, settingState), nextState));
  };

  var formatMessage = getFormatMessage();
  useEffect(function () {
    /** 如果不是浏览器 都没有必要做了 */
    if (!isBrowser()) return;
    if (disableUrlParams) return;

    if (firstRender.current) {
      firstRender.current = false;
      return;
    }
    /** 每次从url拿最新的防止记忆 */


    var urlSearchParams = new URLSearchParams(window.location.search);
    var params = Object.fromEntries(urlSearchParams.entries());
    var diffParams = getDifferentSetting(_objectSpread(_objectSpread({}, params), settingState));
    delete diffParams.logo;
    delete diffParams.menu;
    delete diffParams.title;
    delete diffParams.iconfontUrl;
    delete diffParams.pwa;
    setUrlParams(diffParams);
  }, [setUrlParams, settingState, urlParams, pathname, disableUrlParams]);
  var baseClassName = "".concat(prefixCls, "-setting");
  return _jsx(Drawer, {
    visible: show,
    width: 300,
    closable: false,
    onClose: function onClose() {
      return setShow(false);
    },
    placement: "right",
    getContainer: getContainer,
    handler: _jsx("div", {
      className: "".concat(baseClassName, "-drawer-handle"),
      onClick: function onClick() {
        return setShow(!show);
      },
      children: show ? _jsx(CloseOutlined, {
        style: {
          color: '#fff',
          fontSize: 20
        }
      }) : _jsx(SettingOutlined, {
        style: {
          color: '#fff',
          fontSize: 20
        }
      })
    }),
    style: {
      zIndex: 999
    },
    children: _jsxs("div", {
      className: "".concat(baseClassName, "-drawer-content"),
      children: [_jsx(Body, {
        title: formatMessage({
          id: 'app.setting.pagestyle',
          defaultMessage: 'Page style setting'
        }),
        prefixCls: baseClassName,
        children: _jsx(BlockCheckbox, {
          prefixCls: baseClassName,
          list: [{
            key: 'light',
            title: formatMessage({
              id: 'app.setting.pagestyle.light',
              defaultMessage: '亮色菜单风格'
            })
          }, {
            key: 'dark',
            title: formatMessage({
              id: 'app.setting.pagestyle.dark',
              defaultMessage: '暗色菜单风格'
            })
          }, {
            key: 'realDark',
            title: formatMessage({
              id: 'app.setting.pagestyle.realdark',
              defaultMessage: '暗色菜单风格'
            })
          }].filter(function (item) {
            if (item.key === 'dark' && settingState.layout === 'mix') return false;
            if (item.key === 'realDark' && !enableDarkTheme) return false;
            return true;
          }),
          value: navTheme,
          configType: "theme",
          onChange: function onChange(value) {
            return changeSetting('navTheme', value);
          }
        }, "navTheme")
      }), colorList !== false && _jsx(Body, {
        title: formatMessage({
          id: 'app.setting.themecolor',
          defaultMessage: 'Theme color'
        }),
        prefixCls: baseClassName,
        children: _jsx(ThemeColor, {
          colorList: colorList,
          value: genStringToTheme(primaryColor),
          formatMessage: formatMessage,
          onChange: function onChange(color) {
            return changeSetting('primaryColor', color);
          }
        })
      }), !themeOnly && _jsxs(_Fragment, {
        children: [_jsx(Divider, {}), _jsx(Body, {
          prefixCls: baseClassName,
          title: formatMessage({
            id: 'app.setting.navigationmode'
          }),
          children: _jsx(BlockCheckbox, {
            prefixCls: baseClassName,
            value: layout,
            configType: "layout",
            list: [{
              key: 'side',
              title: formatMessage({
                id: 'app.setting.sidemenu'
              })
            }, {
              key: 'top',
              title: formatMessage({
                id: 'app.setting.topmenu'
              })
            }, {
              key: 'mix',
              title: formatMessage({
                id: 'app.setting.mixmenu'
              })
            }],
            onChange: function onChange(value) {
              return changeSetting('layout', value);
            }
          }, "layout")
        }), _jsx(LayoutSetting, {
          settings: settingState,
          changeSetting: changeSetting
        }), _jsx(Divider, {}), _jsx(Body, {
          prefixCls: baseClassName,
          title: formatMessage({
            id: 'app.setting.regionalsettings'
          }),
          children: _jsx(RegionalSetting, {
            settings: settingState,
            changeSetting: changeSetting
          })
        }), _jsx(Divider, {}), _jsx(Body, {
          prefixCls: baseClassName,
          title: formatMessage({
            id: 'app.setting.othersettings'
          }),
          children: _jsx(List, {
            split: false,
            renderItem: renderLayoutSettingItem,
            dataSource: [{
              title: formatMessage({
                id: 'app.setting.weakmode'
              }),
              action: _jsx(Switch, {
                size: "small",
                className: "color-weak",
                checked: !!colorWeak,
                onChange: function onChange(checked) {
                  changeSetting('colorWeak', checked);
                }
              })
            }]
          })
        }), hideHintAlert && hideCopyButton ? null : _jsx(Divider, {}), hideHintAlert ? null : _jsx(Alert, {
          type: "warning",
          message: formatMessage({
            id: 'app.setting.production.hint'
          }),
          icon: _jsx(NotificationOutlined, {}),
          showIcon: true,
          style: {
            marginBottom: 16
          }
        }), hideCopyButton ? null : _jsx(Button, {
          block: true,
          icon: _jsx(CopyOutlined, {}),
          style: {
            marginBottom: 24
          },
          onClick: function () {
            var _onClick = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
              return _regeneratorRuntime().wrap(function _callee2$(_context2) {
                while (1) {
                  switch (_context2.prev = _context2.next) {
                    case 0:
                      _context2.prev = 0;
                      _context2.next = 3;
                      return navigator.clipboard.writeText(genCopySettingJson(settingState));

                    case 3:
                      message.success(formatMessage({
                        id: 'app.setting.copyinfo'
                      }));
                      _context2.next = 8;
                      break;

                    case 6:
                      _context2.prev = 6;
                      _context2.t0 = _context2["catch"](0);

                    case 8:
                    case "end":
                      return _context2.stop();
                  }
                }
              }, _callee2, null, [[0, 6]]);
            }));

            function onClick() {
              return _onClick.apply(this, arguments);
            }

            return onClick;
          }(),
          children: formatMessage({
            id: 'app.setting.copy'
          })
        })]
      })]
    })
  });
};

export default SettingDrawer;